package edu.buaa.resourceManager.store.db.mapper;

import edu.buaa.resourceManager.vo.CustomProperty;
import edu.buaa.resourceManager.vo.FileEntity;
import edu.buaa.resourceManager.vo.ResourcePath;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

/**
 * Created by sjh on 17-7-1.
 */
public interface FileEntityMapper
{
    @Insert("INSERT into file_entity (`size`, sha512, md5_head, create_t, update_t) " +
            "VALUES(#{size}, #{sha512}, #{headMd5}, #{createTime}, #{lastModifiedTime})")
    @Options(useGeneratedKeys=true) //https://stackoverflow.com/questions/4283159
    int create(FileEntity entity);



    @Select("SELECT * FROM file_entity WHERE id=#{id}")
    @Results(value = {
            @Result(property = "headMd5", column = "md5_head"),
            @Result(property = "createTime",column = "create_t"),
            @Result(property = "lastModifiedTime",column = "update_t")
    })
    FileEntity getById(int id);



    @Select("SELECT * FROM file_entity WHERE id=#{id}")
    @Results(value = {
            @Result(property = "id", column = "id"),
            @Result(property = "headMd5", column = "md5_head"),
            @Result(property = "createTime",column = "create_t"),
            @Result(property = "lastModifiedTime",column = "update_t"),
            @Result(property = "properties", column = "id", javaType = List.class, many = @Many(select = "getPropertyByEntityId"))
    })
    FileEntity getByIdWithPropNoPath(int id);


    @Select("SELECT id FROM file_entity WHERE sha512=#{sha512} LIMIT 1")
    List<FileEntity> getIdBySha512(String sha512);

    @Select("SELECT * FROM file_entity WHERE sha512=#{sha512} LIMIT 1")
    @Results(value={
            @Result(property = "paths",
                    column = "id",
                    many = @Many(
                            select = "edu.buaa.resourceManager.store.db.mapper.ResourcePathMapper.getByEntityId",
                            fetchType = FetchType.EAGER
                    )
            )
    })
    List<FileEntity> getPathDetailsBySha512(String sha512);



    @Select("SELECT * FROM properties WHERE type='entity' AND target_id=#{id}")
    List<CustomProperty> getPropertyByEntityId(int id);



    @Insert("INSERT into properties (`type`, target_id, name, value) " +
            "VALUES('entity', #{targetId}, #{name}, #{value})")
    @Options(useGeneratedKeys=true) //https://stackoverflow.com/questions/4283159
    int addProperty(CustomProperty property);

}
